package com.contact;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.adpter.ChatMsgViewAdapter;
import com.android.ocean.util.common.StringUtil;
import com.android.ocean.view.XListView;
import com.android.ocean.view.XListView.IXListViewListener;
import com.common.method.ChatHelper;
import com.common.method.CommonData;
import com.common.method.ServerPath;
import com.db.DBService;
import com.http.ChatMsgAddTask;
import com.http.ChatMsgListTask;
import com.http.UploadFileTask;
import com.http.UserInfoTask;
import com.matang.R;
import com.matang.jpsh.ExampleUtil;
import com.modle.ChatMsgStruct;
import com.modle.User;
import com.pyq.PyqMainFragment;
import com.util.AppUtil;
import com.util.FileUtils;
import com.util.SoundMeter;
import com.util.UserUtil;
import com.util.VoiceSaveThread;

public class ChatActivity extends BaseActivity implements IXListViewListener,
OnClickListener, ChatMsgListTask.CallBack, ChatMsgAddTask.CallBack,
UploadFileTask.CallBack ,UserInfoTask.CallBack{

	private MessageReceiver mMessageReceiver;
	public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";


	String tag = "ChatActivity";
	private ImageView imgAdd;
	private Button mBtnSend;
	private TextView mBtnRcd;
	// private Button mBtnBack;
	private EditText mEditTextContent;
	private RelativeLayout mBottom;
	private XListView mListView;
	private ChatMsgViewAdapter mAdapter;
	private List<ChatMsgStruct> msgStructList = new ArrayList<ChatMsgStruct>();
	private boolean isShosrt = false;
	private LinearLayout voice_rcd_hint_loading, voice_rcd_hint_rcding,
	voice_rcd_hint_tooshort;
	private ImageView img1, sc_img1;
	private SoundMeter mSensor;
	private View rcChat_popup;
	private LinearLayout del_re;
	private ImageView chatting_mode_btn, volume;
	private boolean btn_vocie = false;
	private int flag = 1;
	private Handler mHandler = new Handler();
	private String voiceName;
	private long startVoiceT, endVoiceT;

	User uiUser;
	User fiUser;
	// 获取更多的FLAG
	private final String REQFLAG_LATEST = "latest";
	// 获取以前Flag
	private final String REQFLAG_OLD = "old";
	public static boolean isForeground = false;
	private final int GOT_MSG = 999;
	private final int TIME_INTERAL = 1000 * 5;// 30s取一次
	private Handler handler = new Handler() {



		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GOT_MSG: {
				loadMsgListDataLatest();
				//	handler.sendEmptyMessageDelayed(GOT_MSG, TIME_INTERAL);
			}
			}
		}

	};
	private Timer timer;
	protected void onDestroy() {
		super.onDestroy();
		timer.cancel();
	};

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
				String messge = intent.getStringExtra(KEY_MESSAGE);
				String extras = intent.getStringExtra(KEY_EXTRAS);
				StringBuilder showMsg = new StringBuilder();
				showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
				if (!ExampleUtil.isEmpty(extras)) {
					showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
				}
				setCostomMsg(showMsg.toString());
			}
		}
	}


	private String uriToPath(Uri uri){

		String[] proj = { MediaStore.Images.Media.DATA };

		Cursor actualimagecursor = managedQuery(uri,proj,null,null,null);

		int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

		actualimagecursor.moveToFirst();

		String img_path = actualimagecursor.getString(actual_image_column_index);
		return img_path;

	}

	//添加视频
	private void addVedio() {
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0.5);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, "mp4");
		startActivityForResult(intent, 1);
	}


	private String videoPath;
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == 1) {
			if (data != null) {
				Uri uri = data.getData();
				videoPath = uriToPath(uri);
				if (videoPath != null) {
					File newfile = new File(videoPath);
					String name = newfile.getName();
					String path =videoPath.substring(0,videoPath.lastIndexOf("/"))+"/";
					uploadVoice(path, name);
				}

			}

		}

		if (requestCode == 100) {
			if (data == null) {
				return;
			}
			Uri uri = data.getData();
			String path = FileUtils.getPath(this, uri);
			File newfile = new File(path);
			String name = newfile.getName();
			String mypath =path.substring(0,path.lastIndexOf("/"))+"/";
			uploadVoice(mypath, name);
		}
	}


	private void showFileChooser() {

		Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 

		intent.setType("*/*"); 

		intent.addCategory(Intent.CATEGORY_OPENABLE);



		try {

			startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), 100);

		} catch (android.content.ActivityNotFoundException ex) {

			Toast.makeText(this, "Please install a File Manager.",  Toast.LENGTH_SHORT).show();

		}

	}

	@SuppressWarnings("deprecation")
	private void showSelect(){

//	
//		showFileChooser();
//		alertDialog.dismiss();
		final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		View view = getLayoutInflater().inflate(R.layout.select_dialog, null);
		TextView tvWj = (TextView) view.findViewById(R.id.tv_wj);
		TextView tvSp = (TextView) view.findViewById(R.id.tv_sp);
		tvWj.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				showFileChooser();
				alertDialog.dismiss();
				
			}
		});
		tvSp.setOnClickListener(new OnClickListener() {
			

			public void onClick(View arg0) {
				addVedio();
				alertDialog.dismiss();
				
			}
		});
		alertDialog.setView(view);
		alertDialog.show();
	}

	private void setCostomMsg(String msg){

		Toast.makeText(getApplicationContext(), msg, 1).show();
	}

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		registerReceiver(mMessageReceiver, filter);
	}
	private String thumb = "";
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_chat);
		registerMessageReceiver();
		loadUserData();
		timer = new Timer();

		// 启动activity时不自动弹出软键盘
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		init();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {

				handler.sendEmptyMessage(GOT_MSG);
			}
		}, 1000, TIME_INTERAL);

	}

	void init() {
		mContext = ChatActivity.this;
		fiUser = (User) getIntent().getSerializableExtra("user");
		uiUser = UserUtil.readUser();
		String userId = uiUser.id;
		Set<String> tagSet = new LinkedHashSet<String>();
		tagSet.add(userId);
		 JPushInterface.setAliasAndTags(getApplicationContext(), userId, tagSet, new TagAliasCallback() {
			
		
			public void gotResult(int arg0, String arg1, Set<String> arg2) {
				//Toast.makeText(getApplicationContext(), "注册到极光推送成功", 1).show();
				
			}
		});

		findViews();
		initPaneData();
	}

	@Override
	protected void findViews() {
		super.findViews();
		imgAdd = (ImageView) findViewById(R.id.img_send);
		mListView = (XListView) findViewById(R.id.listview);
		mListView.setPullLoadEnable(false);
		mListView.setXListViewListener(this);
		mBtnSend = (Button) findViewById(R.id.btn_send);
		mBtnRcd = (TextView) findViewById(R.id.btn_rcd);
		mBtnSend.setOnClickListener(this);
		mBottom = (RelativeLayout) findViewById(R.id.btn_bottom);
		chatting_mode_btn = (ImageView) this.findViewById(R.id.ivPopUp);
		volume = (ImageView) this.findViewById(R.id.volume);
		rcChat_popup = this.findViewById(R.id.rcChat_popup);
		img1 = (ImageView) this.findViewById(R.id.img1);
		sc_img1 = (ImageView) this.findViewById(R.id.sc_img1);
		del_re = (LinearLayout) this.findViewById(R.id.del_re);
		voice_rcd_hint_rcding = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_rcding);
		voice_rcd_hint_loading = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_loading);
		voice_rcd_hint_tooshort = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_tooshort);
		mSensor = new SoundMeter();
		mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);
		if (mAdapter == null) {
			mAdapter = new ChatMsgViewAdapter(this, msgStructList);
			mListView.setAdapter(mAdapter);
		}
		imgAdd.setOnClickListener(new OnClickListener() {
			
	
			public void onClick(View arg0) {
				showSelect();
				
			}
		});
	}

	@Override
	protected void initPaneData() {

		super.initPaneData();
		header.headLeftTv.setText("返回");
		if (StringUtil.isNull(fiUser.name)) {
			header.headTitleTv.setText(StringUtil.mobileEncry(fiUser.mobile));
		} else {
			header.headTitleTv.setText(fiUser.name);
		}
		header.headRightTv.setText("查看");
		header.headRightTv.setVisibility(View.VISIBLE);
		header.headRightTv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent intent = new Intent(ChatActivity.this, UserSimpleInfoActivity.class);
				intent.putExtra("fUserID", fiUser);
				startActivity(intent);
//				showSelect();

			}
		});

		// 语音文字切换按钮
		chatting_mode_btn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				if (btn_vocie) {
					mBtnSend.setVisibility(View.VISIBLE);
					mBottom.setVisibility(View.VISIBLE);
					mBtnRcd.setVisibility(View.GONE);
					imgAdd.setVisibility(View.GONE);
					mEditTextContent.setVisibility(View.VISIBLE);
					btn_vocie = false;
					chatting_mode_btn
					.setImageResource(R.drawable.chatting_setmode_msg_btn);

				} else {
					mBtnSend.setVisibility(View.GONE);
					mEditTextContent.setVisibility(View.GONE);
					imgAdd.setVisibility(View.VISIBLE);
					mBtnRcd.setVisibility(View.VISIBLE);
					mBottom.setVisibility(View.VISIBLE);
					chatting_mode_btn
					.setImageResource(R.drawable.chatting_setmode_voice_btn);
					btn_vocie = true;
				}
			}
		});
		mBtnRcd.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				// 按下语音录制按钮时返回false执行父类OnTouch
				return false;
			}
		});
		loadMsgListDataLatest();
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_send:
			String content = mEditTextContent.getText().toString();
			mEditTextContent.setText("");
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			String date = df.format(new Date());
			ChatMsgStruct chatMsgStruct = new ChatMsgStruct("", date, content, false);
			chatMsgStruct.setThumb(thumb);
			msgStructList.add(chatMsgStruct);
			mAdapter.notifyDataSetChanged();
			sendDataToServer(content, "text");
			break;
		case R.id.headRight:
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), PyqMainFragment.class);
			startActivity(intent);
			//			if (fiUser.type.equalsIgnoreCase(User.U_TYPE_ORG)) {
			//				Bundle b = new Bundle();
			//				b.putSerializable("userID", fiUser.id);
			//				TranHelper.toAct(mContext, OrgInfoActivity.class, b);
			//			} else {
			//				Bundle b = new Bundle();
			//				b.putSerializable("fUserID", fiUser.id);
			//				b.putInt("FromFlag", FromFlag.USER_SIMPLEINFO_CHAT);
			//				//TranHelper.toAct(mContext, UserSimpleInfoActivity.class, b);
			//
			//			}
			break;
		}
	}

	@Override
	protected void onPause() {
		handler.removeMessages(GOT_MSG);
		super.onPause();
	}

	@Override
	protected void onResume() {
		// handler.sendEmptyMessageDelayed(GOT_MSG, TIME_INTERAL);
		super.onResume();
	}

	private String getDate() {
		Calendar c = Calendar.getInstance();

		String year = String.valueOf(c.get(Calendar.YEAR));
		String month = String.valueOf(c.get(Calendar.MONTH));
		String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);
		String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
		String mins = String.valueOf(c.get(Calendar.MINUTE));

		StringBuffer sbBuffer = new StringBuffer();
		sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":"
				+ mins);

		return sbBuffer.toString();
	}

	// 按下语音录制按钮时
	@Override
	public boolean onTouchEvent(MotionEvent event) {

		if (!Environment.getExternalStorageDirectory().exists()) {
			Toast.makeText(this, "No SDCard", Toast.LENGTH_LONG).show();
			return false;
		}

		if (btn_vocie) {
			System.out.println("1");
			int[] location = new int[2];
			mBtnRcd.getLocationInWindow(location); // 获取在当前窗口内的绝对坐标
			int btn_rc_Y = location[1];
			int btn_rc_X = location[0];
			int[] del_location = new int[2];
			del_re.getLocationInWindow(del_location);
			int del_Y = del_location[1];
			int del_x = del_location[0];
			if (event.getAction() == MotionEvent.ACTION_DOWN && flag == 1) {
				if (!Environment.getExternalStorageDirectory().exists()) {
					// 没有SD卡，不可用
					Toast.makeText(this, "No SDCard", Toast.LENGTH_LONG).show();
					return false;
				}
				System.out.println("2");
				if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {// 判断手势按下的位置是否是语音录制按钮的范围内
					System.out.println("3");
					// startVoiceT = SystemClock.currentThreadTimeMillis();
					startVoiceT = System.currentTimeMillis();
					mBtnRcd.setBackgroundResource(R.drawable.voice_rcd_btn_pressed);
					rcChat_popup.setVisibility(View.VISIBLE);
					voice_rcd_hint_loading.setVisibility(View.VISIBLE);
					voice_rcd_hint_rcding.setVisibility(View.GONE);
					voice_rcd_hint_tooshort.setVisibility(View.GONE);
					mHandler.postDelayed(new Runnable() {
						public void run() {
							if (!isShosrt) {
								voice_rcd_hint_loading.setVisibility(View.GONE);
								voice_rcd_hint_rcding
								.setVisibility(View.VISIBLE);
							}
						}
					}, 300);
					img1.setVisibility(View.VISIBLE);
					del_re.setVisibility(View.GONE);
					voiceName = startVoiceT + ".amr";
					start(voiceName);
					flag = 2;
				}
			} else if (event.getAction() == MotionEvent.ACTION_UP && flag == 2) {// 松开手势时执行录制完成
				System.out.println("4");
				mBtnRcd.setBackgroundResource(R.drawable.voice_rcd_btn_nor);
				if (event.getY() >= del_Y
						&& event.getY() <= del_Y + del_re.getHeight()
						&& event.getX() >= del_x
						&& event.getX() <= del_x + del_re.getWidth()) {
					rcChat_popup.setVisibility(View.GONE);
					img1.setVisibility(View.VISIBLE);
					del_re.setVisibility(View.GONE);
					stop();
					flag = 1;
					File file = new File(ChatHelper.getVoiceSavePath()
							+ voiceName);
					if (file.exists()) {
						file.delete();
					}
				} else {

					voice_rcd_hint_rcding.setVisibility(View.GONE);
					stop();
					// endVoiceT = SystemClock.currentThreadTimeMillis();
					endVoiceT = System.currentTimeMillis();
					flag = 1;
					int time = (int) ((endVoiceT - startVoiceT) / 1000);
					if (time < 1) {
						isShosrt = true;
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.GONE);
						voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
						mHandler.postDelayed(new Runnable() {
							public void run() {
								voice_rcd_hint_tooshort
								.setVisibility(View.GONE);
								rcChat_popup.setVisibility(View.GONE);
								isShosrt = false;
							}
						}, 500);
						return false;
					}
					rcChat_popup.setVisibility(View.GONE);

					uploadVoice(ChatHelper.getVoiceSavePath(), voiceName);

				}
			}
			if (event.getY() < btn_rc_Y) {// 手势按下的位置不在语音录制按钮的范围内
				System.out.println("5");
				Animation mLitteAnimation = AnimationUtils.loadAnimation(this,
						R.anim.cancel_rc);
				Animation mBigAnimation = AnimationUtils.loadAnimation(this,
						R.anim.cancel_rc2);
				img1.setVisibility(View.GONE);
				del_re.setVisibility(View.VISIBLE);
				del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg);
				if (event.getY() >= del_Y
						&& event.getY() <= del_Y + del_re.getHeight()
						&& event.getX() >= del_x
						&& event.getX() <= del_x + del_re.getWidth()) {
					del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg_focused);
					sc_img1.startAnimation(mLitteAnimation);
					sc_img1.startAnimation(mBigAnimation);
				}
			} else {

				img1.setVisibility(View.VISIBLE);
				del_re.setVisibility(View.GONE);
				del_re.setBackgroundResource(0);
			}
		}
		return super.onTouchEvent(event);
	}

	private static final int POLL_INTERVAL = 300;

	private Runnable mSleepTask = new Runnable() {
		public void run() {
			stop();
		}
	};
	private Runnable mPollTask = new Runnable() {
		public void run() {
			double amp = mSensor.getAmplitude();
			updateDisplay(amp);
			mHandler.postDelayed(mPollTask, POLL_INTERVAL);

		}
	};

	private void start(String name) {
		mSensor.start(name);
		mHandler.postDelayed(mPollTask, POLL_INTERVAL);
	}

	private void stop() {
		mHandler.removeCallbacks(mSleepTask);
		mHandler.removeCallbacks(mPollTask);
		mSensor.stop();
		volume.setImageResource(R.drawable.amp1);
	}

	private void updateDisplay(double signalEMA) {

		switch ((int) signalEMA) {
		case 0:
		case 1:
			volume.setImageResource(R.drawable.amp1);
			break;
		case 2:
		case 3:
			volume.setImageResource(R.drawable.amp2);

			break;
		case 4:
		case 5:
			volume.setImageResource(R.drawable.amp3);
			break;
		case 6:
		case 7:
			volume.setImageResource(R.drawable.amp4);
			break;
		case 8:
		case 9:
			volume.setImageResource(R.drawable.amp5);
			break;
		case 10:
		case 11:
			volume.setImageResource(R.drawable.amp6);
			break;
		default:
			volume.setImageResource(R.drawable.amp7);
			break;
		}
	}

	/**
	 * 
	 * @Description:TODO插入最近联系人
	 * @param
	 * @return void
	 * @author zhuw
	 * @date 2013-8-22 下午5:17:42
	 */
	public void insertRecordDB() {
		System.out.println("-----------------insertRecordDB");
		DBService.inserOrUpdateUser(mContext, uiUser.id, fiUser);
	}

	/**
	 * 
	 * @Description:TODO
	 * @param@param content
	 * @param@param type
	 * @return void
	 * @author zhuw
	 * @date 2013-8-19 下午8:58:35
	 */
	private void sendDataToServer(String content, String type) {
		if (StringUtil.isNull(content)) {
			AppUtil.tsMsg(mContext, "内容不能为空");
		} else {
			showProgressDialog("发送中...");
			new ChatMsgAddTask(this, fiUser.thumb, uiUser.thumb).execute(
					uiUser.id, fiUser.id, type, content);

		}

	}

	/**
	 * 
	 * @Description:TODO上传声音文件
	 * @param@param path
	 * @param@param name
	 * @return void
	 * @author zhuw
	 * @date 2013-8-19 下午8:42:30
	 */
	private void uploadVoice(String path, String name) {
		showProgressDialog("上传中...");
		new UploadFileTask(this).execute(path, name);
	}

	/**
	 * 
	 * @Description:TODO第一次进入加载数据
	 * @param
	 * @return void
	 * @author zhuw
	 * @date 2013-8-19 下午10:05:28
	 */
	// private void loadMsgListDataFirst() {
	// showProgressDialog("数据加载中...");
	// new ChatMsgListTask(REQFLAG_LATEST,this).execute(uiUser.id, fiUser.id,
	// CommonData.DEAULT_PAGESIZE, "", "");
	// }

	private void loadMsgListDataLatest() {
		Log.d(tag, "自动获取数据loadMsgListDataLatest。。。。");
		if (StringUtil.isListNull(msgStructList)) {
			new ChatMsgListTask(REQFLAG_LATEST, this, fiUser.thumb,
					uiUser.thumb).execute(uiUser.id, fiUser.id,
							CommonData.DEAULT_PAGESIZE, "", "");
		} else {
			new ChatMsgListTask(REQFLAG_LATEST, this, fiUser.thumb,
					uiUser.thumb).execute(uiUser.id, fiUser.id,
							CommonData.DEAULT_PAGESIZE, "",
							msgStructList.get(msgStructList.size() - 1).date);
		}

	}

	/**
	 * 
	 * @Description:TODO加载过去数据
	 * @param
	 * @return void
	 * @author zhuw
	 * @date 2013-8-19 下午11:22:58
	 */
	private void loadMsgListDataOld() {
		Log.d(tag, "上拉加载过去的数据。。。。");
		if (StringUtil.isListNull(msgStructList)) {
			new ChatMsgListTask(REQFLAG_OLD, this, fiUser.thumb, uiUser.thumb)
			.execute(uiUser.id, fiUser.id, CommonData.DEAULT_PAGESIZE,
					"", "");
		} else {
			new ChatMsgListTask(REQFLAG_OLD, this, fiUser.thumb, uiUser.thumb)
			.execute(uiUser.id, fiUser.id, CommonData.DEAULT_PAGESIZE,
					msgStructList.get(0).date, "");
		}

	}

	/**
	 * 
	 * @Description:TODO填充数据
	 * @param
	 * @return void
	 * @author zhuw
	 * @date 2013-8-19 下午11:23:22
	 */
	private void fillListPane(int selectPos) {
		if (StringUtil.isListNull(msgStructList)) {
			AppUtil.tsMsg(mContext, "没有聊天记录");
		} else {
			
			mAdapter.notifyDataSetChanged();
			mListView.setSelection(selectPos);
		}

	}

	@Override
	public void procError(String msg) {
		dismissProgressDialog();
		AppUtil.tsMsg(mContext, msg);

	}

	@Override
	public void procChatMsgListFailed(String reqFlag, String msg) {
		dismissProgressDialog();
		AppUtil.tsMsg(mContext, msg);

	}

	@Override
	public void procChatMsgListData(String reqFlag,
			ArrayList<ChatMsgStruct> dataList) {
		dismissProgressDialog();
		if (reqFlag == REQFLAG_LATEST) {
			// 加载最新数据
			if (!StringUtil.isListNull(dataList)) {
				for (int i = dataList.size() - 1; i >= 0; i--) {
					downVoice(dataList.get(i));
				}
				this.msgStructList.addAll(dataList);
				updateListStatus();
				// 设置选中最新数据
				fillListPane(msgStructList.size() - 1);
			}
		} else {
			// 加载以前的数据
			mListView.stopRefresh();
			mListView.stopXlistView();
			if (StringUtil.isListNull(dataList)) {
				// 没有数据或者获取的数据小于1页的大小
				mListView.setPullRefreshEnable(false);
			} else {
				if (dataList.size() < Integer
						.parseInt(CommonData.DEAULT_PAGESIZE)) {
					mListView.setPullRefreshEnable(false);
				} else {
					mListView.setPullRefreshEnable(true);
				}
				msgStructList.addAll(0, dataList);
				// 设置选择下来的前几天
				fillListPane(dataList.size() - 1);
			}

		}

	}

	/**
	 * 
	 * @Description:TODO根据msgStructList的size，更新listview.其能否下拉刷新
	 * @param
	 * @return void
	 * @author zhuw
	 * @date 2013-8-19 下午11:07:47
	 */
	private void updateListStatus() {
		if (msgStructList.size() == Integer
				.parseInt(CommonData.DEAULT_PAGESIZE)) {
			mListView.setPullRefreshEnable(true);
		} else {
			mListView.setPullRefreshEnable(false);
		}
	}

	@Override
	public void procChatMsgAddData(ChatMsgStruct data) {
		dismissProgressDialog();
		downVoice(data);
		this.msgStructList.add(data);
		updateListStatus();
		fillListPane(msgStructList.size() - 1);
		mEditTextContent.setText("");
		insertRecordDB();

	}

	/**
	 * 
	 * @Description:TODO下载声音，如果含有.amr，则标志是声音文件，则下载
	 * @param@param data
	 * @return void
	 * @author zhuw
	 * @date 2013-8-19 下午9:49:46
	 */
	private void downVoice(ChatMsgStruct data) {
		if (data.getText().contains(".amr")) {
			new VoiceSaveThread(ServerPath.SERVER + data.getText()).start();
		}
	}

	@Override
	public void procChatMsgAddFailed(String msg) {
		dismissProgressDialog();
	//	AppUtil.tsMsg(mContext, msg);

	}
	private void loadUserData() {
		User user = UserUtil.readUser();
		if (user == null) {
			return;
		}
		new UserInfoTask(this).execute(user.id);
	}

	@Override
	public void procUploadFile(String result) {
		dismissProgressDialog();
		try {
			JSONObject jo = new JSONObject(result);
			sendDataToServer(jo.getString("src"), "voice");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		Log.d(tag, result);

	}

	@Override
	public void onRefresh() {
		loadMsgListDataOld();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub

	}

	@Override
	public void procUploadFileError(String result) {
		dismissProgressDialog();
		AppUtil.tsMsg(mContext, "文件上传失败");

	}

	@Override
	public void procUserInfoData(User data) {
		if (data != null) {
			thumb = data.thumb;
		}
		
	}

	@Override
	public void procUserInfoError(String msg) {
		// TODO Auto-generated method stub
		
	}

}